<!--
 @description 任务详情
 @fileName Detail.vue
 @author zengqiongying
 @created 2023/06/12 15:59:08
-->
<template>
  <div :class="{ 'has-foot-pb': showOperatorBar }" style="padding-top: 8px">
    <Card>
      <template #title>
        <div class="card-title">
          <span class="main-title">{{ detail.sadAddress }} </span>
          <span
            :class="[
              'color-normal',
              {
                'color-normal': detail.statusName === '验收中',
                'color-error': detail.statusName === '已退回',
                'color-grey': detail.statusName === '已提交' || detail.statusName === '已完成'
              }
            ]"
          >
            {{ detail.statusName }}
          </span>
        </div>
      </template>
      <Cell
        size="mini"
        :border="false"
        :labelBlack="false"
        title="门店名称"
        :modelValue="detail.agentName"
        readonly
        custom
      />
      <Cell size="mini" :border="false" :labelBlack="false" title="门店编码" :modelValue="detail.storeCode" readonly />
      <Cell size="mini" :border="false" :labelBlack="false" title="总面积" custom readonly>
        {{ toThousands(detail.totalArea) }}m²
      </Cell>
      <Cell size="mini" :border="false" :labelBlack="false" title="验收面积" custom readonly>
        {{ toThousands(detail.acceptArea) }}m²
      </Cell>
      <Cell
        size="mini"
        :border="false"
        :labelBlack="false"
        title="装修项目号"
        :modelValue="detail.renovationProjectNo"
        readonly
      />
      <Cell
        size="mini"
        :border="false"
        :labelBlack="false"
        title="异常数量"
        :modelValue="detail.abnorNumber"
        readonly
      />
      <Cell
        size="mini"
        :border="false"
        :labelBlack="false"
        title="验收人员"
        :modelValue="detail.ysSpecialist"
        readonly
      />
      <Cell
        v-if="detail.reportMold === '软装'"
        size="mini"
        :border="false"
        :labelBlack="false"
        title="形象督导"
        :modelValue="detail.supervisionImage"
        readonly
      />
      <Cell
        v-if="detail.reportMold === '硬装'"
        size="mini"
        :border="false"
        :labelBlack="false"
        title="工程监理"
        :modelValue="detail.projectSupervision"
        readonly
      />
      <Cell
        v-if="detail.ysStartTime"
        size="mini"
        :border="false"
        :labelBlack="false"
        title="开始时间"
        :modelValue="parseTime(detail.ysStartTime, '{y}/{m}/{d}')"
        readonly
      />
      <Cell
        v-if="detail.ysEndTime && ['已提交', '已完成'].includes(detail.statusName)"
        size="mini"
        :border="false"
        :labelBlack="false"
        title="完成时间"
        :modelValue="parseTime(detail.ysEndTime, '{y}/{m}/{d}')"
        readonly
      />
    </Card>
    <Card title="参与人员合照">
      <Cell title="" is-column custom readonly>
        <PartnerPhoto v-if="photoList.length > 0" :modelValue="photoList" readonly />
      </Cell>
    </Card>
    <Card title="异常验收" class="card-abnormal-area">
      <AbnormalItem
        v-for="(item, i) in abnormalList"
        :key="`${i}-${item.said}`"
        :detail="item"
        :name="`异常${i + 1}`"
        :readonly="['已完成', '已提交'].includes(detail.statusName)"
        @delete="onAbnormalDelete(item.said)"
      />
      <template v-if="['验收中', '已退回'].includes(detail.statusName)">
        <!-- 进行中的验收任务可新增 -->
        <div class="pd-lr-main" style="margin-top: 8px">
          <qmp-button block round class="ctm-btn-main-outline radius-xl" @click="onAddAbnormal">添加异常</qmp-button>
        </div>
      </template>
    </Card>
    <Card :title="`${detail.acceptMold || ''}区域`" class="card-ys-area">
      <ModuleItem
        v-for="(item, i) in moduleList"
        :key="`${i}-${item.amid}`"
        :detail="item"
        :readonly="['已完成', '已提交'].includes(detail.statusName)"
        @delete="onModuleDelete(item.amid)"
        @edit="onEditModule(item)"
      />
      <template v-if="!isReView && ['验收中', '已退回'].includes(detail.statusName)">
        <!-- 仅验收操作可新增 -->
        <div class="pd-lr-main" style="margin-top: 8px">
          <qmp-button block round class="ctm-btn-main-outline radius-xl" @click="onEditModule()">添加区域</qmp-button>
        </div>
      </template>
    </Card>

    <div v-if="showOperatorBar" :class="['ctm-content-foot']">
      <template v-if="detail.statusName === '未派发' && pageSource === 'task'">
        <!-- 来自任务管理：分配验收人员，软装和硬装：开始验收/复查-->
        <div v-if="!detail.ysSpecialist" class="btn radius-larg ctm-btn-main" @click="onAllocation">
          分配{{ isReView ? '复查' : '验收' }}人员
        </div>
        <div v-else class="btn radius-larg ctm-btn-main" @click="onStartAccept">
          开始{{ isReView ? '复查' : '验收' }}
        </div>
      </template>
      <template v-else-if="['验收中', '复查中', '已退回'].includes(detail.statusName)">
        <!-- 验收中：移交/提交 ; 复查中：移交-->
        <!-- <template v-if="isReView">
          <div class="btn radius-larg ctm-btn-main" @click="onTransfer">移交</div>
        </template>
        <template v-else> -->
        <div class="btn radius-larg ctm-btn-warning" @click="onTransfer">移交</div>
        <div class="btn radius-larg ctm-btn-main" @click="onSubmit">提交</div>
        <!-- </template> -->
      </template>
      <template v-else-if="detail.statusName === '已提交' && pageSource === 'task'">
        <!-- 来自任务管理的可操作：退回/ 复查 -->
        <div class="btn radius-larg ctm-btn-error" @click="onReturnBack">退回</div>
      </template>
      <template v-else-if="detail.statusName === '已完成' && pageSource === 'task'">
        <div class="btn radius-larg ctm-btn-warning" @click="onReview">复查</div>
      </template>
    </div>

    <ModuleAdd
      v-if="detail.caid"
      :caid="detail.caid"
      :detail="activeModuleData"
      v-model:show="showModule"
      @success="refreshData"
    />
    <TaskAllocation :baseInfo="detail" v-model:show="showAllocation" @success="onAllocationSuccess" />
    <TaskTransfer :baseInfo="detail" v-model:show="showTransfer" @success="onTransferSuccess" />
    <TaskReview :baseInfo="detail" v-model:show="showReview" @success="onReviewSuccess" />
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick, computed } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import AbnormalItem from '@/views/components/Abnormal/Item.vue'
  import ModuleItem from '@/views/components/Module/Item.vue'
  import ModuleAdd from '@/views/components/Module/Add.vue'
  import TaskReview from '@/views/components/Task/Review.vue'
  import TaskTransfer from '@/views/components/Task/Transfer.vue'
  import TaskAllocation from '@/views/components/Task/Allocation.vue'
  import PartnerPhoto from '@/views/components/PartnerPhoto/index.vue'

  import { IAnyKeyObject } from '@/types/common'
  import { toThousands, parseTime, formatURL } from '@/utils'
  import { queryTaskDetail } from '@/apis/Task'
  import { TaskCommit, TaskReturn, ModuleDelete, AbnormalDelete } from '@/mixins/TaskCommon'

  export default {
    name: 'TaskDetail',
    components: {
      Card,
      Cell,
      PartnerPhoto,
      AbnormalItem,
      ModuleItem,
      ModuleAdd,
      TaskReview,
      TaskTransfer,
      TaskAllocation
    },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $router = useRouter()
      const $route = useRoute()
      const datas = reactive<IAnyKeyObject>({
        caid: $route.query.id || '',
        pageSource: $route.query.source || '', // task 任务管理 ， soft 软装 ， hard 硬装
        detail: {},
        showAllocation: false,
        showReview: false,
        showTransfer: false,
        showModule: false,
        activeModuleData: {},
        abnormalList: [],
        moduleList: [],
        photoList: []
      })
      // 是否复查
      const isReView = computed(() => {
        return datas.detail.acceptMold && datas.detail.acceptMold.indexOf('复查') > -1 ? true : false
      })
      // 是否显示操作栏
      const showOperatorBar = computed(() => {
        if (datas.pageSource === 'task') {
          return ['未派发', '已提交', '已完成', '已退回'].includes(datas.detail.statusName)
        }
        return ['验收中', '已退回'].includes(datas.detail.statusName)
        //[1, '1', 3, '3'].includes(detail.statue)
        // statue =1 /3 不可编辑
      })

      const getDetailData = (id?: any) => {
        const caid = id || datas.caid
        queryTaskDetail(caid).then((res) => {
          const d = res.data || {}
          datas.detail = d
          if (d.acceptModules && d.acceptModules.length) {
            datas.moduleList = d.acceptModules
              .map((v: any) => {
                return {
                  ...v,
                  ...{ acceptMold: d.acceptMold }
                }
              })
              .sort((a: any, b: any) => {
                return a.sortNumber - b.sortNumber
              })
          } else {
            datas.moduleList = []
          }
          if (d.abnormals && d.abnormals.length) {
            datas.abnormalList = (d.abnormals || []).sort((a: any, b: any) => {
              return a.sortNumber - b.sortNumber
            })
          } else {
            datas.abnormalList = []
          }
          if (d.files && d.files.length) {
            datas.photoList = d.files || []
          } else {
            datas.photoList = []
          }
        })
      }
      // 分配
      const onAllocation = () => {
        datas.showAllocation = true
      }
      // 复查
      const onReview = () => {
        datas.showReview = true
      }
      // 移交
      const onTransfer = () => {
        datas.showTransfer = true
      }
      // 提交
      const onSubmit = () => {
        let empty = false
        datas.moduleList.forEach((v: any) => {
          if (Number(v.facadeNumber || 0) === 0) {
            empty = true
          }
        })
        if (empty) {
          proxy.$toast('存在立面为0的验收区域，不可提交')
          return
        }
        TaskCommit(datas.caid, () => {
          // refreshData()
          $router.goBack()
        })
      }
      // 退回
      const onReturnBack = (row: any) => {
        TaskReturn(datas.caid, () => {
          // refreshData()
          $router.goBack()
        })
      }
      // 删除异常
      const onAbnormalDelete = (id: string) => {
        AbnormalDelete(id, () => {
          refreshData()
        })
      }

      // 删除模块
      const onModuleDelete = (id: string) => {
        ModuleDelete(id, () => {
          refreshData()
        })
      }
      // 添加异常
      const onAddAbnormal = () => {
        $router.push({
          path: '/abnormal/edit',
          query: {
            caid: datas.caid
          }
        })
      }
      const onEditModule = (d: any) => {
        // 新增/编辑区域
        datas.activeModuleData = d && d.amid ? d : {}
        nextTick(() => {
          datas.showModule = true
        })
      }

      // 开始验收/开始复查
      const onStartAccept = () => {
        $router.replace({
          path: '/task/edit',
          query: {
            source: $route.query.source,
            id: datas.caid
          }
        })
      }

      // 刷新当前数据(包括缓存页面对应的验收项)
      const refreshData = () => {
        getDetailData()
        proxy.$SimpleEvents.emit('refreshTaskItem')
      }
      // 移交成功
      const onTransferSuccess = () => {
        // proxy.$SimpleEvents.emit('refreshTaskList')

        // 移交操作成功后，返回列表时，tab切换到“2 验收中”
        proxy.$SimpleEvents.emit('changeTaskListTab', '2')
        $router.goBack()
      }
      // 复查发起成功
      const onReviewSuccess = () => {
        $router.goBack()
      }
      // 分配成功
      const onAllocationSuccess = () => {
        // 分配操作成功后，返回列表时，tab切换到“1 未派发”
        proxy.$SimpleEvents.emit('changeTaskListTab', '1')
        $router.goBack()
      }

      onBeforeRouteLeave((to, from, next) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (['TaskManagement', 'HardCheckAccept', 'SoftCheckAccept', 'Index'].includes(toName)) {
          $store.commit('routerKeep/removeCache', instanceName)
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
        }
        next()
      })

      proxy.$SimpleEvents.registerEvent('refreshTaskDetail', (id: any) => {
        if (!id) return
        getDetailData(id)
      })

      getDetailData()

      return {
        ...toRefs(datas),
        isReView,
        showOperatorBar,
        toThousands,
        parseTime,
        formatURL,
        onReview,
        onTransfer,
        onAllocation,
        onReturnBack,
        refreshData,
        onModuleDelete,
        onAbnormalDelete,
        onEditModule,
        onAddAbnormal,
        onSubmit,
        onStartAccept,
        onTransferSuccess,
        onReviewSuccess,
        onAllocationSuccess
      }
    }
  }
</script>
<style lang="less" scoped>
  .card-title {
    padding: 0 16px;
    margin-bottom: 4px;
    display: flex;
    justify-content: space-between;
    font: var(--font-main-body);
    .main-title {
      flex: 1;
      margin-right: 5px;
    }
  }
  .card-abnormal-area {
    padding-left: 16px;
    padding-right: 16px;
    /deep/ .group-title {
      margin-bottom: 8px;
      padding: 0;
    }
    /deep/ .c-cell.flex-column .label {
      font: var(--font-main-title-body);
      color: var(--texticon-default-strong);
    }
  }
  .card-ys-area {
    padding-left: 16px;
    padding-right: 16px;
    /deep/ .group-title {
      margin-bottom: 8px;
      padding: 0;
    }
    /deep/ .c-cell.flex-column .label {
      font: var(--font-main-strengthen);
      color: var(--texticon-default-strong);
    }
  }
  .user-imgs {
    display: flex;
    align-items: center;
    .img-item {
      position: relative;
      margin-right: 8px;
      width: 56px;
      height: 56px;
      border-radius: var(--radius-l);
      background: #e9ecec;
      border-radius: var(--radius-l);
      overflow: hidden;
    }
  }
</style>
